#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <strings.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>

#define PORT 8888
void deal(int connfd);
int main()
{
	struct sockaddr_in server;
	int ret;
	pthread_t tid;
	bzero(&server,sizeof(server));
	server.sin_family = AF_INET;
	inet_pton(AF_INET,"127.0.0.1",&server.sin_addr);
	server.sin_port = htons(PORT);
	
	int listenfd = socket(AF_INET, SOCK_STREAM , 0 );
	assert(listenfd>=0);
	ret = bind(listenfd, (struct sockaddr*)&server , sizeof(server));
	assert(ret != -1);
	ret = listen(listenfd , 5);
	assert(ret !=-1);
	struct sockaddr_in  client;
	int client_len = sizeof(client);
	while(1)
	{
		int connfd = accept(listenfd , (struct sockaddr *)&client , &client_len);
		if(pthread_create(&tid, NULL , deal , (void *)connfd)) //why not &connfd		
		{
			printf("create pthread error \n");
			exit(0);
		}


	}
	close(listenfd);
	return 0;
}	


void deal(int connfd)
{
	
	printf("begin read");
	int n;
	char rbuffer[1024];
	char wbuffer[1024];
	while(1)
	{
		if((n=read(connfd,rbuffer,1024))==0)
		{	
			printf("read error!");
			continue;
		}else{
			printf("read size if %d \n",n);
			rbuffer[n]='\0';
			printf("read data is %s \n",rbuffer);
			sprintf(wbuffer,"write the read data %s",rbuffer);
			write(connfd,wbuffer,sizeof(wbuffer));		
		}
	
	
	}


}


